// 基础URL，用于连接后端API
// const BASE_URL = 'http://localhost:9090';
const BASE_URL = 'https://f.insightlearning.org.cn';

/**
 * 发送请求的封装
 * @param {String} url - 请求地址
 * @param {String} method - 请求方法
 * @param {Object} data - 请求数据
 * @param {Boolean} loading - 是否显示加载中
 */
const request = (url, method = 'GET', data = {}, loading = true) => {
  // 显示加载中
  if (loading) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
  }

  // 返回Promise
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + url,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        // 成功
        if (res.data.code === '200') {
          resolve(res.data.data);
        } else {
          // 业务错误
          wx.showToast({
            title: res.data.msg || '请求失败',
            icon: 'none',
            duration: 2000
          });
          reject(res.data);
        }
      },
      fail: (err) => {
        // 网络错误
        wx.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none',
          duration: 2000
        });
        reject(err);
      },
      complete: () => {
        // 请求完成，隐藏加载中
        if (loading) {
          wx.hideLoading();
        }
      }
    });
  });
};

module.exports = {
  request,
  get: (url, data, loading) => request(url, 'GET', data, loading),
  post: (url, data, loading) => request(url, 'POST', data, loading),
  put: (url, data, loading) => request(url, 'PUT', data, loading),
  delete: (url, data, loading) => request(url, 'DELETE', data, loading)
}; 